package com.myz.rabbitmq.autoAck;

import com.myz.rabbitmq.utils.ConnectionUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.MessageProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 消息分发者
 *
 * @author maoyz on 18-4-4.
 */
public class NewTask {
    private static final Logger logger = LoggerFactory.getLogger(NewTask.class);

    private static final String TASK_QUEUE_NAME = "work_queue";

    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = ConnectionUtils.getConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);

        // 消费者发送确认消息前，消息队列不发送消息，保证一次只分发一个
        int prefetchCount = 1;
        channel.basicQos(prefetchCount);

        //分发信息
        for (int i = 0; i < 20; i++) {
            String message = "Hello RabbitMQ --> " + i;
            channel.basicPublish("",
                    TASK_QUEUE_NAME,
                    MessageProperties.PERSISTENT_TEXT_PLAIN,
                    message.getBytes());

            logger.debug("NewTask send '" + message + "'");

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        channel.close();
        connection.close();
    }
}
